#!/usr/bin/python

import sys
import bsddb
import cStringIO


def parse_origin(s):
    f = cStringIO.StringIO(s)
    orig_started = False
    origin = ''
    for line in f:
        if orig_started:
            if line.startswith('//'):
                break
            else:
                origin += ''.join(line.strip().split()[1:])
        if line.startswith('ORIGIN'):
            orig_started = True
    else:
        return ''
    return origin

if __name__ == "__main__":
 
    raw_db_fname = sys.argv[1]
    genom_db_fname = sys.argv[2]

    cnt_all = 0
    cnt_success = 0
    raw_db = bsddb.hashopen(raw_db_fname, 'r')
    genom_db = bsddb.hashopen(genom_db_fname, 'w')
    for key, value in raw_db.iteritems():
        cnt_all += 1
        origin = parse_origin(value)
        if not origin:
            print >> sys.stderr, 'Empty origin for locus %s' % key
            continue
        genom_db[key] = origin
        cnt_success += 1

    raw_db.close()
    genom_db.sync()
    genom_db.close()

    print "Done! (%s/%s)" % (cnt_success, cnt_all)

